package com.central.apps.controller;

import com.central.app.service.HandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private HandlerService handlerService;
    @PostMapping("/orderController")
    public List<Map<String,Object>> orderController(@RequestBody Map<String,Object> data) {
        String id = MapUtils.getString(data, "id");
        String ponum = MapUtils.getString(data, "ponum");
        String code="1";
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
        if (CollectionUtils.isNotEmpty(bySql)){
            for (int i=0;i<bySql.size();i++){
                Map<String, Object> map = bySql.get(i);
                String id1 = MapUtils.getString(map, "id");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_posline where id='" + id1 + "'");
                Map<String, Object> map1 = bySql1.get(0);
                String ppslid = MapUtils.getString(map1, "ppslid");
                Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//会总行订单数量
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select a.* from gq_posline a left join gq_po t on t.id=a.poid where a.ppslid ='" + ppslid + "' and t.status!='新建' and t.status!='已作废'");//根据计划会总行id查询所有订单会总行的数量
                float orderqtys=0;
                if (CollectionUtils.isNotEmpty(bySql2)){
                    for (int j=0;j<bySql2.size();j++){
                        Map<String, Object> map2 = bySql2.get(j);
                        Float orderqty = MapUtils.getFloat(map2, "orderqty");
                        Float rejectedQty = MapUtils.getFloat(map2, "rejectedqty");
                        // 采购订单实际有效的数量=订单数量-退货数量
                        orderqtys =orderqtys + (orderqty-rejectedQty) + orderqty1;
                    }
                    handlerService.updateBySql("update gq_posline set innum="+orderqtys+" where id='" + id1 + "'");
                }
            }
        }
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
        return bySql1;
    }
}
